package cc.linker.steplink.crm.merchant.controller.mall;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchant.service.mall.MallsService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/shopping/mall")
@RestController
public class MallsController {

    @Autowired
    private MallsService mallsService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 获取供货商信息
     *
     * @param session
     * @return
     */
    @GetMapping("/mallinfo")
    public Map<String, Object> mallInfo(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        Map<String, Object> result = mallsService.getMallInfo(param);
        if (StringUtils.isEmpty(result)) {
            return new HashMap<>();
        } else {
            return result;
        }
    }

    /**
     * 开通供货商城
     *
     * @param session
     */
    @GetMapping("/openMall")
    public void openMall(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
            param.put("type", "2");
        } else {
            param.put("customerId", orgId);
            param.put("type", "1");
        }
        param.put("orgId", orgId);
        mallsService.openMall(param);
    }

    /**
     * 编辑保存供货商信息
     *
     * @param param
     * @param session mallLogo，mallName，mallInfo，mallPhone，mallTelephone
     */
    @PostMapping("/savemallinfo")
    public void saveMallInfo(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        mallsService.saveMallInfo(param);
    }

    /**
     * 供货商商品列表
     *
     * @param goodsName
     * @param goodsStatus
     * @param pageIndex
     * @param pageSize
     * @param session
     * @return
     */
    @GetMapping("/goodslist")
    public PageInfo goodsList(
            @RequestParam(value = "goodsName", required = false) String goodsName,
            @RequestParam(value = "goodsStatus", required = false) Integer goodsStatus,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request
    ) throws UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
            param.put("type", "2");
        } else {
            param.put("customerId", orgId);
            param.put("type", "1");
        }
        param.put("orgId", orgId);
        if (!StringUtils.isEmpty(goodsName)) {
            goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            goodsName = goodsName.replaceAll("%", "/%");
            param.put("goodsName", goodsName);
        }
        if (!StringUtils.isEmpty(goodsStatus)) {
            param.put("goodsStatus", goodsStatus);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(mallsService.goodsList(param));
    }

    /**
     * 供货商移除商品
     */
    @PostMapping("/delete")
    public void delete(@RequestBody Map<String, Object> params) {
        Long[] goodsIds =(Long[]) ConvertUtils.convert( params.get("goodsIds").toString().split(","),Long.class);
        mallsService.delete(goodsIds);
    }

    /**
     * 供货商推广
     */
    @PostMapping("/changestatus")
    public void changeStatus(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if(StringUtils.isEmpty(params.get("goodsIds"))){
            throw GlobalException.build("请选择商品");
        }
        Long[] goodsIds =(Long[]) ConvertUtils.convert( params.get("goodsIds").toString().split(","),Long.class);
        Integer goodsStatus =(Integer) params.get("goodsStatus");
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);

        // 判断是否完善了供货商信息
        Map<String, Object> result = mallsService.getMallInfo(param);
        if (StringUtils.isEmpty(result.get("mallName"))) {
            throw GlobalException.build("请先完善供货商信息");
        }
        // 判断是否完成商品配置
        List<Map<String, Object>> goodsListStatus = mallsService.getGoodsListStatus(goodsIds);
        if (goodsListStatus.size() > 0) {
            String goods = "";
            for (Map<String, Object> item : goodsListStatus){
                goods+=","+item.get("goodsId").toString();
            }
            throw GlobalException.build("请先完成商品配置:未配置的商品ID："+goods.substring(1));
        }
        // 修改推广状态
        mallsService.changeStatus(goodsIds, goodsStatus);
    }


    /**
     * 判断供货商是否亏损提示
     * @param params
     * @param session
     */
    @PostMapping("/checkgoodsrewetting")
    public void checkGoodsRewetting(@RequestBody Map<String, Object> params) {
        mallsService.checkGoodsRewetting(params);
    }

    /**
     * 推广商品 加入推广时 判断是否亏损
     * @param params
     * @param session
     */
    @PostMapping("/checkrewetting")
    public void checkRewetting(@RequestBody Map<String, Object> params)
    {
        //现在保存供货商的时候已经判断了
        return;
//        if(StringUtils.isEmpty(params.get("goodsIds"))){
//            throw GlobalException.build("请选择商品");
//        }
//        String orgId = userinfo.getOrgId();
//        Integer goodsStatus =(Integer) params.get("goodsStatus");
//        if(goodsStatus==2){
//            //下架不做判断
//            return;
//        }
//        Long[] goodsIds =(Long[]) ConvertUtils.convert( params.get("goodsIds").toString().split(","),Long.class);
//        mallsService.checkRewetting(goodsIds,orgId);
    }

    /**
     * 供货商品导入
     */
    @PostMapping("/addmallsgoods")
    public void addMallsGoods(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Long[] goodsIds =(Long[]) ConvertUtils.convert( params.get("goodsIds").toString().split(","),Long.class);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
            param.put("type", "2");
        } else {
            param.put("customerId", orgId);
            param.put("type", "1");
        }
        param.put("orgId", orgId);
        for(Long a : goodsIds){
            param.put("goodsId", a);
            mallsService.addMallsGoods(param);
        }
    }

    /**
     * 供货商城首页
     *
     * @param order
     * @param sort
     * @param classificationId
     * @param keywords
     * @param mallsAmountMin
     * @param mallsAmountMax
     * @param pageIndex
     * @param pageSize
     * @param session
     * @return
     */
    @GetMapping("/mallsgoodslist")
    public PageInfo mallsGoodsList(
            @RequestParam(value = "id", defaultValue = "", required = false) Integer id,
            @RequestParam(value = "order", defaultValue = "", required = false) Integer order,
            @RequestParam(value = "sort", defaultValue = "desc", required = false) String sort,
            @RequestParam(value = "classificationId", defaultValue = "", required = false) Integer classificationId,
            @RequestParam(value = "keywords", defaultValue = "", required = false) String keywords,
            @RequestParam(value = "mallsAmountMin", defaultValue = "", required = false) String mallsAmountMin,
            @RequestParam(value = "mallsAmountMax", defaultValue = "", required = false) String mallsAmountMax,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request
    ) throws UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        int payMode = userinfo.getPayMode();
        param.put("payMode",payMode);
        param.put("orgId", orgId);
        param.put("order", order);
        param.put("sort", sort);
        if (!StringUtils.isEmpty(keywords)) {
            keywords = URLDecoder.decode(keywords.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            keywords = keywords.replaceAll("%", "/%");
        }
        param.put("keywords", keywords);
        // 供货商ID
        param.put("id", id);
        param.put("classificationId", classificationId);
        param.put("mallsAmountMin", mallsAmountMin);
        param.put("mallsAmountMax", mallsAmountMax);
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);
        return mallsService.mallsGoodsList(param);
    }

    /**
     * 商品id获取供货商信息
     * @param goodsId
     * @return
     */
    @GetMapping("/mallinfobygoodsid")
    public Map<String, Object> mallInfoByGoodsId(Long goodsId) {
        Integer id = mallsService.getMallIdByGoodsId(goodsId);
        if(id==null){
            throw GlobalException.build("供货商城未开通");
        }
        return mallsService.mallInfoById(id);
    }

    /**
     * 供货商id获取供货商信息
     * @param id
     * @return
     */
    @GetMapping("/mallinfobyid")
    public Map<String, Object> mallInfoById(Integer id) {
        return mallsService.mallInfoById(id);
    }

    /**
     * 获取供货商品状态
     */
    @GetMapping("/getmallsgoodsstatus")
    public Map<String,Object> getMallsGoodsStatus(Long goodsId, HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
            param.put("type", "2");
        } else {
            param.put("customerId", orgId);
            param.put("type", "1");
        }
        param.put("orgId", orgId);
        param.put("goodsId", goodsId);
        return mallsService.getMallsGoodsStatus(param);
    }

    /**
     * 供货商品添加至商城
     */
    @GetMapping("/addgoodsshop")
    public void addGoodsShop(String goodsId,String groupIds,Integer classificationId,HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if(StringUtils.isEmpty(groupIds) || StringUtils.isEmpty(classificationId)){
            throw GlobalException.build("请选择类目与分组");
        }
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
            param.put("type", "2");
        } else {
            param.put("customerId", orgId);
            param.put("type", "1");
        }
        param.put("orgId", orgId);
        param.put("goodsId", goodsId);
        param.put("groupIds", groupIds);
        param.put("classificationId", classificationId);
        mallsService.addGoodsShop(param);
    }


    /**
     * 管理中心
     * 供货商品列表
     */
    @GetMapping("/centermallslist")
    public PageInfo centerMallsList(
            @RequestParam(value = "goodsName", defaultValue = "", required = false) String goodsName,
            @RequestParam(value = "orgId", defaultValue = "", required = false) String orgId,
            @RequestParam(value = "mallsName", defaultValue = "", required = false) String mallsName,
            @RequestParam(value = "isHot", defaultValue = "", required = false) Integer isHot,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request
    ) throws UnsupportedEncodingException {
        Map<String, Object> param = new HashMap<>();
        if (!StringUtils.isEmpty(goodsName)) {
            goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            goodsName = goodsName.replaceAll("%", "/%");
        }
        param.put("goodsName", goodsName);
        param.put("orgId", orgId);
        if (!StringUtils.isEmpty(mallsName)) {
            mallsName = URLDecoder.decode(mallsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            mallsName = mallsName.replaceAll("%", "/%");
        }
        param.put("mallsName", mallsName);
        param.put("isHot", isHot);
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);
        return mallsService.centerMallsList(param);
    }

    /**
     * 获取联汇支付模式的机构列表 paymode=3
     * @return
     */
    @GetMapping("/getlinkerorglist")
    public List<String> getLinkerOrgList()
    {
        return mallsService.getLinkerOrgList();
    }

    /**
     * 管理中心
     * goodsId 商品id
     * sort  0取消置顶 1置顶
     * 供货商品置顶 取消置顶
     */
    @GetMapping("/handletopsort")
    public void handleTopSort(String goodsId,Integer sort)
    {
        mallsService.handleTopSort(goodsId,sort);
    }


    /**
     * 管理中心
     * goodsId 商品 id
     * sort 0 向下 1 向上
     * 供货商品排序
     */
    @GetMapping("/handlenormalsort")
    public void handleNormalSort(String goodsId, Integer sort)
    {
        mallsService.handleNormalSort(goodsId,sort);
    }


    /**
     * 管理中心
     * 供货商品 热门推荐 取消热门
     */
    @GetMapping("/mallsgoodschangehot")
    public void mallsGoodsChangeHot(String goodsId)
    {
        mallsService.mallsGoodsChangeHot(goodsId);
    }

}